<script setup>

import {onMounted, ref , watch} from 'vue'
import { ElMessage } from 'element-plus'
import { queryPageApi,addEmpApi,getEmpByIdApi,updateByIdApi,deletebyIdsApi } from '@/api/emps'
import {queryAllApi} from '@/api/dept'




const searchEmp=ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
})

const empList=ref([])
//定义分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const size='default'
const disabled = false
const background = true


  // 侦听
  // 1)侦听的变量
  // 2)回调函数 
//侦听searchEmp中的date属性
watch(() => searchEmp.value.date,(newValue, oldValue) => {
  //确认用户是否选择了开始日期和结束日期
     if(newValue.length == 2){
      searchEmp.value.begin = newValue[0]
      searchEmp.value.end = newValue[1]
     }else {
      searchEmp.value.begin = ''
      searchEmp.value.end = ''
     }
  })

  //这两段代码分别用于处理分页组件的 每页条数变化 和 当前页码变化，更新分页参数并重新发起查询请求。
  
const handleSizeChange = (val) => {
  //当用户在分页组件中选择“每页显示多少条”时触发
  console.log(`每页 ${val} 条`)
  //将当前页重置为第一页，避免跳转到不存在的页。
  currentPage.value = 1
  //更新每页显示条数
  pageSize.value=val
   //调用 handleSearch() 重新加载数据。
  handleSearch()
}

const handleCurrentChange = (val) => {
   //当用户点击分页组件切换页码时触发。
  console.log(`当前页: ${val}`)
  // 更新当前页码（currentPage.value = val）。
  currentPage.value = val
  // 调用 handleSearch() 加载对应页码的数据。
  handleSearch()
}

const handleSearch =async () => {
  // 处理查询逻辑,调用的接口
  let result = await queryPageApi(searchEmp.value.name, searchEmp.value.gender, searchEmp.value.begin, searchEmp.value.end, currentPage.value, pageSize.value)
//将结果存入到List集合，empList
  empList.value = result.data.rows
//分页数据完善
  total.value = result.data.total
}

const handleReset = () => {
  // 清空表单
  searchEmp.value = {
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
  }
  handleSearch()
}

//新增或修改弹框
const dialogShow = ref(false)
const tips = ref('')
//展示弹框
const showDialog = ()=>{
  //zhanshi
  dialogShow.value = true
  //弹框标题设置
  tips.value = '新增员工'
formData.value={
      image: '',
      username: '',
      name: '',
      gender: null,
      job: null,
      entryDate: '',
      deptName: null,
      phone: '',
      salary: 0,
      exprList: []
  }

}
//定义表单对象，接收新增数据
  const formData=ref({
      image: '',
      username: '',
      name: '',
      gender: null,
      job: null,
      entryDate: '',
      deptName: null,
      phone: '',
      salary: 0,
      exprList: []
  })
//性别数据
const genderList = ref([
  {id:'1',name:'男'},
  {id:'2',name:'女'}
])
  // 职位数据
  const jobList=ref([
    {id:'1',name:'讲师'},
    {id:'2',name:'班主任'},
    {id:'3',name:'就业指导'},
    {id:'4',name:'其他'},
  ])
  //部门数据
  const deptList = ref([])
 // 加载所有部门
  const loadAllDepts=async()=>{
    let result = await queryAllApi()
    deptList.value=result.data
  }

// 文件上传
    // 预览图片地址：imageUrl
    // const imageUrl=ref(null)

  // 文件上传成功，调用的方法：handleAvatarSuccess
  // response  后台响应数据

  const handleAvatarSuccess = (
    response,   
    uploadFile
  ) => {
    // 将预览图片换成响应的图片
    formData.value.image =response.data
  }

   // 文件上传前调用的方法：beforeAvatarUpload
  const beforeAvatarUpload= (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
      ElMessage.error('图片格式必须是JPG格式!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('图片最大大小是2MB!')
      return false
    }
    return true
  }
  // 新增工作经历
  const addWork=()=>{
    formData.value.exprList.push({
      "begin": "",
      "end": "",
      "company": "",
      "job": ""
    })
  }
   // 删除指定工作履历   index:索引
  const deleteWork=(index)=>{
    // 1：删除1次
    formData.value.exprList.splice(index,1)
  }

      // 深度侦听
  watch(()=>formData.value.exprList,(newValue,oldValue)=>{
    //循环新数据
    formData.value.exprList.forEach((item,index)=>{ 
      if(item.date){
        item.begin = newValue[index].date[0]
        item.end = newValue[index].date[1]
      }
    })
  },{deep:true})

  //5）表单校验实现
  //关联表单对象
  const ruleFormRef=ref(null)
  //定义校验规则（光标离开后时间校验）
  // 验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/g, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});


  //提交表单校验
const addEmp=async()=>{
   if (!ruleFormRef) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    let result = null
    if (valid) {

      //远程调用
      //根据formData的id判断是否为空，是新增还是修改，id不为空则是修改
      if(formData.value.id){
        //修改
        result = await updateByIdApi(formData.value)
      }else{
        //新增
        result = await addEmpApi(formData.value)
      }


    
    } else {
      console.log('提交失败!', fields)
    }
    //判断结果
    //刷新并关闭弹窗
    
    
    if(result.code){
      dialogShow.value=false
      handleSearch()
      //提示
      ElMessage.success('操作成功！')
    }else{
      ElMessage.error('操作失败')
    }


  })
}

//6）添加员工保存实现
//在api中创建保存员工的方法
//导入api的方法
//新增员工的函数中，调用api方法
//操作成功，则刷新界面（重新获取员工列表），关闭弹窗
//操作失败，错误信息



// 操作处理
const handleEdit = async (id) => {
  console.log('Edit:', id)
  const result = await getEmpByIdApi(id);
  formData.value=result.data
  //弹窗
  dialogShow.value = true


  //工作履历 date【】 begin/end
  formData.value.exprList.forEach((item,index)=>{
    item.date=[]
    item.date.push(item.begin)
    item.date.push(item.end)
  })
}
//处理所有选中的信息

//处理所有选中的行信息
// const handleSelectionChange = (selection) => {
//   console.log('selection:', selection)
//   let idCollection = selection.map(function (item) {
//     return item.id

//   })
//   console.log('idCollection:', idCollection)  
// }

//处理所有选中的信息


const deleteIds = ref([])

const handleSelectionChange = (selection)=>{
  let idCollection = selection.map((item=>item.id))
  deleteIds.value = idCollection
}
//单个删除操作
const deleteById = (id) =>{
  deleteIds.value = [id]
  deleteByIds()
}
//批量删除操作
const deleteByIds= async()=>{
  let result = await deletebyIdsApi(deleteIds.value)
  handleSearch()
}

const token = ref({token:''})
const getToken = () =>{
  let userInfo =localStorage.getItem('loginUser')
  if(userInfo){
    token.value.token = JSON.parse(userInfo).token
  }
}


 
onMounted(()=>{
  handleSearch()
  loadAllDepts()
  getToken()
})

</script>

<template>



 
  <el-dialog
    v-model="dialogShow"
    :title="tips"
    width="800"
    :before-close="handleClose"
  >
  <!-- 用于获取 <el-form> 实例的引用，以便调用其方法如 validate() 进行表单验证； -->
  <!-- :rules="rules" 是绑定表单验证规则对象。如果未定义 rules 或未正确使用 ref 调用验证方法，则验证不会生效。 -->
    <el-form
  
      ref="ruleFormRef"
      style="max-width: 800px"
      :model="formData"
      :rules="rules"
      label-width="auto"
  >
  <!-- 待办 -->
   <!--  Element Plus 的布局行组件 -->
  <el-row :gutter="0">
    <!-- :gutter="0" 设置了该行内所有列之间的水平间距为 0，取消默认的 20px 间隙。 -->
        <el-col :span="12">
          <!-- el-col 是 Element Plus 的布局列组件。:span="12" 表示该列占据 12 个栅格宽度。
              整个容器一行最多有 24 个栅格，因此 span=12 表示该列占一半宽度。 
              <el-row :gutter="0">
                <el-col :span="12">左边内容</el-col>
                <el-col :span="12">右边内容</el-col>
              </el-row>
          -->
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input v-model="formData.username" />
            </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="(gen,index) in genderList" :key="index" :label="gen.name" :value="gen.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="job">
            <el-select v-model="formData.job" placeholder="请选择职位"  style="width: 100%;">
              <el-option v-for="(job,index) in jobList" :key="index" :label="job.name" :value="job.id" />
            </el-select>
          </el-form-item>
        </el-col>

            <!-- required什么意思 aria-label 什么意思 -->
          <el-col :span="12">
              <el-form-item label="入职时间" prop="entryDate" required style="width: 100%;">
                      <el-date-picker
                        v-model="formData.entryDate"
                        type="date"
                        aria-label="入职时间"
                        placeholder="请选择入职时间"
                        style="width: 100%"
                      />
                </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="输入薪资" prop="salary">
              <el-input v-model="formData.salary" />
            </el-form-item>
          </el-col>
          <!-- 循环解析 -->
          <el-col :span="12">
              <el-form-item label="部门" prop="deptId">
                  <el-select v-model="formData.deptId" placeholder="请选择部门" style="width: 100%;">
                      <el-option v-for="(dept,index) in deptList" :key="index" :label="dept.name" :value="dept.id" />
                  </el-select>
              </el-form-item>
          </el-col>
          <!-- 用户头像上传 -->
          <el-col :span="24">
              <el-form-item label="头像" prop="image">
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload"
                  :headers="token"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                <!-- 为什么不需要写value -->
                  <img v-if="formData.image" :src="formData.image" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="工作">
              <el-button type="success" @click="addWork">新增工作经历</el-button>
            </el-form-item>
   <!-- v-model="formData.exprList[index].date" -->
            <el-row v-for="(exp,index) in formData.exprList" :key="index"> 
                <el-col :span="10">
                    <el-form-item label="入职时间">
                        <el-date-picker
                          v-model="exp.date"
                          type="daterange"
                          range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          size="default"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="公司名字" prop="company">
                    <el-input v-model="exp.company" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="职位" prop="job">
                    <el-input v-model="exp.job" />
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-button type="danger" @click="deleteWork(index)">删除</el-button>
                </el-col>
            </el-row>
          </el-col>
  </el-row>


  </el-form>
        <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogShow = false">取消</el-button>
        <el-button type="primary" @click="addEmp">
          确认
        </el-button>
      </div>
    </template>

  </el-dialog>

    <h1>员工管理</h1>
  <el-form :inline="true" :model="searchEmp" >
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="请输入员工姓名"/>
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchEmp.gender" placeholder="请选择">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>

    <el-form-item label="入职日期">
       <el-date-picker 
        v-model="searchEmp.date"
        placeholder="选择日期范围"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
    </el-form-item>

     <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button >清空</el-button>
    </el-form-item>
  </el-form>

<el-button type="primary" @click="showDialog">添加员工</el-button>
<el-button type="danger" @click="deleteByIds">批量删除</el-button>

<div class="pdbox">
<el-table :data="empList"  @selection-change="handleSelectionChange" style="width: 100%">
<el-table-column type="selection" width="55" />
  <el-table-column prop="id" label="主键ID" />
 <el-table-column prop="name" label="姓名"  />
 <el-table-column prop="gender" label="性别"  >
    <template #default="scope">

        {{ scope.row.gender==1?'男':'女' }}
    </template>
 </el-table-column>
 <el-table-column prop="image" label="头像" >
    <template #default="scope">
      <el-image :src="scope.row.image" width="100" height="100" />
    </template>
 </el-table-column>
 <el-table-column prop="job" label="职位" >
      <template #default="scope">
        <el-tag v-if="scope.row.job==1">班主任</el-tag>
        <el-tag v-else-if="scope.row.job==2">讲师</el-tag>
        <el-tag v-else-if="scope.row.job==3">学工主管</el-tag>
        <el-tag v-else>其他</el-tag>
      </template>
 </el-table-column>
 <el-table-column prop="salary" label="月薪" ></el-table-column>
 <el-table-column prop="entryDate" label="入职日期" width="180" align="center"></el-table-column>
   <el-table-column prop="deptName" label="部门名称" ></el-table-column>
 <el-table-column fixed="right" label="操作" min-width="120">
  <template #default="scope">
    <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
    <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
  </template>
 </el-table-column>
</el-table>
</div>


    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

      
</template>

<style scoped>
  .pdbox{
    margin-top:50px
  }
</style>

<style>

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>